package CCN::MGW::probe;
# Copyright (C) 2006, 2007  Stephane Alnet
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
# 

#
# For more information visit http://carrierclass.net/
#
use strict; use warnings;

our @__ports = ();

sub ports
{
    __probe() if not @__ports;
    return @__ports;
}

sub cards
{
    __probe() if not @__ports;
    our %cards;
    for my $port (@__ports)
    {
        my $location = $port->{card};
        $cards{$location}->{ports}->{$port->{port}} = $port;
        push @{$cards{$location}->{ports_array}}, $port;
        $cards{$location}->{location}   = $location;
        $cards{$location}->{model}      ||= $port->{model};
        $cards{$location}->{hwec}       ||= $port->{hwec};
        $cards{$location}->{version}    ||= $port->{v};
        $cards{$location}->{cpu}        ||= $port->{cpu};
        $cards{$location}->{irq}        ||= $port->{irq};
    }
    return %cards;
}

sub __probe
{
    # open(PROBE,'/usr/sbin/wanrouter hwprobe verbose |') or die "hwprobe failed: $!";
    open(PROBE,'<','/proc/net/wanrouter/hwprobe_verbose') or die "hwprobe failed: $!";

    my $i = 0;
    while(<PROBE>)
    {
        chomp;
        next unless my ($model,$params) = /^\d+ \. (\S+)\s+: (.*)$/;
        $params =~ s/\s+//g;
        my %params = map { /^\s*(\S+)=(\S+)\s*$/; lc($1) => $2 } split(/:/,$params);

        # 1 . AFT-A108-SH : SLOT=14 : BUS=0 : IRQ=10 : CPU=A : PORT=1 : HWEC=256 : V=33
        # In PCI terms, the locations is bus:slot.id (with id=0 for a Sangoma card it seems).
        $__ports[$i] = {
            index => $i,
            model => $model,
            port_id => "port_${i}", # used by HTML::Template
            card  => $params{bus}.':'.$params{slot},
            %params,
            # Allow one Timeslot Group by default
            # Note: ts_group = "tsg_"+index+"_"+ts_name
            ts_groups => [ # used by HTML::Template
                {
                    ts_group => "tsg_${i}_1",
                    ts_name => "1",
                },
                # {
                #     ts_group => "tsg_${i}_2",
                #     ts_name => "2",
                # },
            ],
        };
        $i++;
    }
    close(PROBE);
}

1;